const client = require('scp2')
const { prompt } = require('inquirer')
const ora = require('ora')

async function getConfig() {
  const questions = [
    {
      type: 'input',
      name: 'username',
      message: '请输入用户名',
      default: 'root'
    },
    {
      type: 'input',
      name: 'password',
      message: '请输入密码'
    }
  ]
  const answers = await prompt(questions)
  return answers
}

const src = 'dist/build/h5/'

const config = {
  port: 22,
  host: '120.26.166.165',
  username: 'root',
  password: '',
  path: '/www/wwwroot/www.yinuosnowball.top/uniH5/'
}

/**
 * @description 上传打包文件到服务器
 * @param {*} src 打包文件路径
 * @param {*} config 服务器配置
 * @param {*} config.port 服务器端口
 * @param {*} config.host 服务器地址
 * @param {*} config.username 服务器用户名
 * @param {*} config.password 服务器密码
 * @param {*} config.path 服务器文件路径
 */
async function uploadDistFile(src, config) {
  const inputConfig = await getConfig()
  let mergeConfig = config
  if (inputConfig.password && inputConfig.username) {
    mergeConfig = { ...config, ...inputConfig }
  }
  let spinner = ora('打包文件上传中...')

  spinner.start()
  client.scp(src, mergeConfig, function (err) {
    spinner.stop()
    if (!err) {
      spinner = ora('打包文件上传成功')
      spinner.succeed()
      return
    }
    spinner = ora('上传失败')
    spinner.fail()
    console.log(err)
  })
}

uploadDistFile(src, config)
